﻿package com.boyiis.sell.controller;

import com.boyiis.sell.enums.ResultEnum;
import com.boyiis.sell.exception.SellException;
import com.boyiis.sell.model.vo.Result;
import com.boyiis.sell.utils.SecurityKitUtil;
import com.boyiis.sell.utils.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxMpService wxOpenService;

    private static final String TOKEN = "boyiis";

    @GetMapping("/validate")
    public String validate(HttpServletRequest request, HttpServletResponse response) {

        //获取请求参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        //1.构造字符串数组
        String[] arr = {this.TOKEN, nonce, timestamp};
        //2.字符串数组排序
        Arrays.sort(arr);
        //3.将排序后的三个字符串拼接成一个字符串
        StringBuffer sb = new StringBuffer();
        for (String str : arr) {
            sb.append(str);
        }

        String sha1 = SecurityKitUtil.sha1(sb.toString());

        if (sha1.equals(signature)) {
            try {
                OutputStream os = response.getOutputStream();
                BufferedWriter resBr = new BufferedWriter(new OutputStreamWriter(os));
                resBr.write(echostr);
                resBr.flush();
                resBr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return echostr;
    }

    @GetMapping("/login")
    public void login(HttpServletResponse response) throws Exception {
        String backUrl = "http://cjp.ngrok.cc/sell/wechat/auth";

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WeixinUtil.APPID +
                "&redirect_uri=" + URLEncoder.encode(backUrl, "UTF-8") +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";

        response.sendRedirect(url);
    }

    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code) {
        log.info("进入auth方法");
        log.info("code={}", code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeixinUtil.APPID +
                "&secret=" + WeixinUtil.APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        Map<String, Object> map = WeixinUtil.get(url);
        String token = (String) map.get("access_token");
        String openid = (String) map.get("openid");

        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token +
                "&openid=" + openid +
                "&lang=zh_CN";

        Map<String, Object> userMap = WeixinUtil.get(userInfoUrl);

    }

    //-----------------------------------------使用sdk方式-----------------------------------------
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        //1.配置
        //2.调用方法
        String url = "http://cjp.ngrok.cc/sell/wechat/userInfo";
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_USER_INFO, URLEncoder.encode("returnUrl"));
        log.info("【微信网页授权获取code】, result={}", redirectUrl);
        return "redirect:" + redirectUrl;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) {
        log.info("【微信网页授权获取用户信息】");
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new SellException(ResultEnum.WX_MP_ERROR.getCode(), e.getError().getErrorMsg());
        }

        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info(openId);

        return "redirect:" + returnUrl + "?openid=" + openId;
    }

    @GetMapping("/qrAuthorize")
    public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) {
        String url = "http://cjp.ngrok.cc/sell/wechat/qrUserInfo";
        String redirectUrl = wxOpenService.buildQrConnectUrl(url, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode("returnUrl"));
        log.info("【微信网页登录授权获取code】, result={}", redirectUrl);
        return "redirect:" + redirectUrl;
    }

    @GetMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) {
        log.info("【微信网页登录授权获取用户信息】");
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页登录授权】{}", e);
            throw new SellException(ResultEnum.WX_MP_ERROR.getCode(), e.getError().getErrorMsg());
        }

        String openId = wxMpOAuth2AccessToken.getOpenId();

        return "redirect:" + returnUrl + "?openid=" + openId;
    }

}





kgt8ON7yVITDhtdwci0qeSFiLVLNoVRj-3eNS4921oBqIul2qok9WDutbckfIsr4ioo-V44YeK0OQAp_9h5uVQ
